package deibay.server.io;

import java.util.List;
import org.jdom.Document;
import org.jdom.Element;

import deibay.users.User;

public class XmlRegisteredUsers {
	
	private Element regist = null;
	private Document doc = null;
	
	public XmlRegisteredUsers()
	{
	}
	
	public void createXmlRegister()
	{	
		doc = new Document();
		regist = new Element("Register");
		doc.setRootElement(regist);		
	}
	
	public User addRegister(String login, String password, String email, String address, String role)
	{
		List<Element> elements = regist.getChildren();
		for(Element e: elements)
		{
			Element userLogin = e.getChild("login");
			if(userLogin.getValue().equals(login))
				return null;
		}
		XmlUser xmlUser = new XmlUser(login, password, email, address, role);			
		regist.addContent(xmlUser.getXmlUser());
		XmlIO.writeXmltoFile(doc, XmlIO.XML_REGISTER);
		return xmlUser.xmlToObject();
	}
	
	public void loadXmlRegister()
	{		
		doc = XmlIO.readXML(XmlIO.XML_REGISTER);
		if(doc == null)
		{
			createXmlRegister();
			XmlIO.writeXmltoFile(doc, XmlIO.XML_REGISTER);
			doc = XmlIO.readXML(XmlIO.XML_REGISTER);
		}
		regist = doc.getRootElement();
	}
		
	public User getUser(String login, String password)
	{
		List<Element> elements = regist.getChildren();
		for(Element e: elements)
		{
			Element userLogin = e.getChild("login");
			if(userLogin.getValue().equals(login))
			{
				Element userPass = e.getChild("pass");
				if(userPass.getValue().equals(password))
				{
					XmlUser xml = new XmlUser(e);
					return xml.xmlToObject();
				}	
				else return null;
			}
				
		}
		
		return null;
	}
}
